import os
import sys
import time

from loguru import logger

from settings import get_root_path

# 格式参考: https://loguru.readthedocs.io/en/stable/api/logger.html
formatter = (
    "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> <level>{level}</level> <cyan>{thread.name}-{thread.id}</cyan> "
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>")


class Logger(object):
    __logger = None

    @classmethod
    def get_logger(cls, fmt: str = formatter) -> logger:
        if cls.__logger is None:
            cls.__logger = logger
            cls.__logger.remove()  # 清空所有设置
            root_path = get_root_path()
            logger_name = f"fast_{time.strftime('%Y-%m-%d', time.localtime()).replace('-', '_')}.log"
            logger_path = os.path.join(root_path, "logs")
            if not os.path.exists(logger_path):
                os.makedirs(logger_path)

            logger_path = os.path.join(logger_path, logger_name)
            cls.__logger.add(sys.stdout, format=fmt)  # 控制台输出

            # 文件输出
            cls.__logger.add(logger_path, format=fmt,
                             retention='1 month',
                             backtrace=True,
                             enqueue=True,
                             rotation="00:00")
        return cls.__logger


log = Logger.get_logger()
